
package com.jeff.tianti.controller;

import com.alibaba.fastjson.JSON;
import com.jeff.tianti.common.dto.AjaxResult;
import com.jeff.tianti.utils.FileUtils;
import com.jeff.tianti.utils.UUIDUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/file")
public class FileUploadController {
    Logger logger = LoggerFactory.getLogger(FileUploadController.class);
    @Value("${file_upload_path}")
    String fileUploadPath;
    @Value("${map_pic_local}")
    String mapPicLocal;

    /*  *
     * @param file 要上传的文件(店铺装修图片上传的接口)
     * @return
     */
//    temporary_table
    @RequestMapping(value = "/fitment/upload", method = RequestMethod.POST)
    public AjaxResult upload(@RequestParam("file") MultipartFile[] files) {
        MultipartFile file = files[0];
        logger.info("图片上传: type");
        String fileName = UUIDUtils.getUUID();
        Map<String, String> map = new HashMap<>();
        String fileFullName = fileName + getFileExtension(file);
        map.put("url", mapPicLocal + "/" + fileFullName);
        map.put("file", fileUploadPath + "/" + fileFullName);
        if (FileUtils.upload(file, fileUploadPath, fileFullName)) {
            // 上传成功，给出页面提示
            logger.info("图片上传结果：" + JSON.toJSONString(map));
            return AjaxResult.setSuccessData(map);
        } else {
            logger.error("图片上传结果：" + JSON.toJSONString(map));
            throw new RuntimeException("图片上传失败");
        }
    }

    public String getFileExtension(MultipartFile cFile) {
        String originalFileName = cFile.getOriginalFilename();
        return originalFileName.substring(originalFileName.lastIndexOf("."));
    }
    /*    *//**
     * @param file 要上传的文件
     * @return
     *//*

    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        logger.info("图片上传: type"  );
        String fileName = UUIDUtils.getUUID();
        ProductPic productPic = new ProductPic();
        String fileFullName = fileName + getFileExtension(file);
        productPic.setPcFile(fileUploadPath + "/" + fileFullName);
        productPic.setPcUrl(mapPicLocal + "/" + fileFullName);
        Result result;
        if (FileUtils.upload(file, fileUploadPath, fileFullName)) {
            // 上传成功，给出页面提示
            result = ResultApi.success(productPic);
            logger.info("图片上传结果：" + JSON.toJSONString(result));
        } else {
            result = ResultApi.fail();
            logger.error("图片上传结果：" + JSON.toJSONString(result));
        }
        return result;
    }

    *//**
     * 产品描述图片上传
     * @param file
     * @return
     *//*

    @PostMapping("/desc/upload")
    public Result productDescUpload(@RequestParam("file") MultipartFile file) {
        String fileName =UUIDUtils.getUUID();
        ProductPic productPic = new ProductPic();
        String fileFullName = fileName + getFileExtension(file);
        productPic.setPcFile(fileUploadPath + "/" + fileFullName);
        productPic.setPcUrl(mapPicLocal + "/" + fileFullName);
        Result result;
        if (FileUtils.upload(file, fileUploadPath, fileFullName)) {
            // 上传成功，给出页面提示
            HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("src", httpDomain+"/"+productPic.getPcUrl());
            result= ResultApi.success(objectObjectHashMap, ResultEnum.FILE_UPLOAD_SUCCESS);
            logger.info("图片上传结果：" + JSON.toJSONString(result));
        } else {
            result= ResultApi.fail(ResultEnum.FILE_UPLOAD_FILE);
            logger.error("图片上传结果：" + JSON.toJSONString(result));
        }
        return result;
    }


    @RequestMapping("/del")
    public Result delFile(@RequestParam String filePath){
        try {
            File file = new File(filePath);
            if (file.delete()) {
                logger.info(file.getName() + "is deleted");
                return ResultApi.success();
            } else {
                logger.info("Delete failed.");
                return ResultApi.fail();
            }
        } catch (Exception e) {
            logger.info("Exception occured");
            e.printStackTrace();
            return ResultApi.fail();
        }
    }

    public String getFileExtension(MultipartFile cFile) {
        String originalFileName = cFile.getOriginalFilename();
        return originalFileName.substring(originalFileName.lastIndexOf("."));
    }*/

}

